package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.pojo.BlackList;
import com.tanhua.common.pojo.Settings;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.MyCenterApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.UserLike;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.*;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class QXMyCenterService {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private TanHuaService tanHuaService;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private IMService imService;

    @Autowired
    private SettingsService settingsService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private BlackListService blackListService;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Reference(version = "1.0.0")
    private MyCenterApi myCenterApi;

    /**
     * 在我的这个模块总通过用户ID查询个人信息
     *
     * @param userId
     * @return
     */
    public UserInfoVo findUserById(Long userId) {
        if (ObjectUtil.isEmpty(userId)) {
            //如果查询id为null，就表示查询当前用户信息
            userId = UserThreadLocal.get().getId();
        }
        //查询用户信息
        UserInfo userInfo = userInfoService.findUserInfo(userId);
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }
        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        userInfoVo.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");

        return userInfoVo;
    }

    /**
     * 更新用户个人信息
     *
     * @param userInfoVo
     * @return
     */
    public Boolean updateInfo(UserInfoVo userInfoVo) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setAge(userInfo.getAge());
        userInfo.setNickName(userInfoVo.getNickname());
        userInfo.setBirthday(userInfoVo.getBirthday());
        userInfo.setSex(ObjectUtil.equals(userInfoVo.getGender(), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setCity(userInfoVo.getCity());
        userInfo.setEdu(userInfoVo.getEducation());
        userInfo.setIncome(StrUtil.replace(userInfoVo.getIncome(), "k", ""));//页面显示没有K,所以做替换一个空字串
        userInfo.setIndustry(userInfoVo.getProfession());
        userInfo.setMarriage(userInfoVo.getMarriage() == 1 ? "已婚" : "未婚");

        return userInfoService.updateUserInfo(userInfo);
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     *
     * @return
     */
    public CountsVo findCounts() {
        User user = UserThreadLocal.get();
        CountsVo countsVo = new CountsVo();
        countsVo.setEachLoveCount(myCenterApi.queryEachLoveCount(user.getId()));
        countsVo.setLoveCount(myCenterApi.queryLoveCount(user.getId()));
        countsVo.setFanCount(myCenterApi.queryFanCount(user.getId()));
        return countsVo;
    }

    /**
     * 互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     *
     * @param type
     * @param nickname
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult findRelationCountList(Integer type, String nickname, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get().getId();
        List<Object> userIdList = null;
        //1 互相关注 2 我关注 3 粉丝 4 谁看过我
        switch (type) {
            case 1:
                List<UserLike> bothLikeList = userLikeApi.findLoveEachOtherList(userId, page, pageSize).getRecords();
                userIdList = CollUtil.getFieldValues(bothLikeList, "userId");
                break;
            case 2:
                List<UserLike> myLikeList = userLikeApi.findMyLikeList(userId, page, pageSize).getRecords();
                userIdList = CollUtil.getFieldValues(myLikeList, "likeUserId");
                break;
            case 3:
                List<UserLike> fansList = userLikeApi.findMyFansList(userId, page, pageSize).getRecords();
                userIdList = CollUtil.getFieldValues(fansList, "userId");
                break;
            case 4:
                List<Visitors> visitorsList = visitorsApi.recentVisitors(userId, page, pageSize).getRecords();
                userIdList = CollUtil.getFieldValues(visitorsList, "visitorUserId");
                break;
            default:
                return pageResult;
        }
        if (CollUtil.isEmpty(userIdList)) {
            return pageResult;
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIdList);
        if (StrUtil.isNotEmpty(nickname)) {//nickname用于用户在列表中搜索目标用户
            queryWrapper.like("nick_name", nickname);
        }
        List<UserInfo> userInfoList = userInfoService.findPageInfo(queryWrapper);

        List<UserLikeListVo> userLikeListVoList = new ArrayList<>();

        for (UserInfo userInfo : userInfoList) {
            UserLikeListVo userLikeListVo = new UserLikeListVo();
            userLikeListVo.setId(userInfo.getUserId());
            userLikeListVo.setAvatar(userInfo.getLogo());
            userLikeListVo.setNickname(userInfo.getNickName());
            userLikeListVo.setGender(userInfo.getSex().name().toLowerCase());
            userLikeListVo.setAge(userInfo.getAge());
            userLikeListVo.setCity(userInfo.getCity());
            userLikeListVo.setEducation(userInfo.getEdu());
            userLikeListVo.setMarriage(StrUtil.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
            //是否喜欢  userLikeApi中的isLike开放出来
            userLikeListVo.setAlreadyLove(userLikeApi.isLike(userId, userInfo.getUserId()));

            Double score = recommendUserService.findScore(userId, userInfo.getUserId());
            userLikeListVo.setMatchRate(Convert.toInt(score));

            userLikeListVoList.add(userLikeListVo);
        }
        pageResult.setItems(userLikeListVoList);
        return pageResult;
    }

    /**
     * 取消喜欢
     * @param userId
     * @return
     */
    public void cancelLike(Long userId) {
        User user = UserThreadLocal.get();
        //判断当前用户与此用户是否相互喜欢
        Boolean like = userLikeApi.bothLikeOther(user.getId(), userId);
        //取消喜欢
        userLikeApi.unLikeUser(user.getId(),userId);
        if(like){
            //取消好友关系，解除在环信平台的好友关系
            imService.removeFriend(userId);
        }
    }

    /**
     * 喜欢
     *
     * @param userId
     */
    public void likeFan(Long userId) {
        //喜欢用户，如果用户是相互喜欢的话就会成为好友
        this.tanHuaService.chooseLike(userId);
    }

    /**
     * 用户设置
     * @return
     */
    public SettingsVo findSettings() {
        SettingsVo settingsVo = new SettingsVo();
        User user = UserThreadLocal.get();

        //设置用户的基本信息
        settingsVo.setId(user.getId());
        settingsVo.setPhone(user.getMobile());

        //查询用户的配置数据
        Settings settings = this.settingsService.querySettings(user.getId());
        if(ObjectUtil.isNotEmpty(settings)){
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
            settingsVo.setLikeNotification(settings.getLikeNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());
        }

        //查询陌生人问题
        settingsVo.setStrangerQuestion(this.tanHuaService.findStrangerQuestion(user.getId()));

        return settingsVo;
    }

    /**
     * 保存问题
     * @param content
     */
    public void saveQuestions(String content) {
        User user = UserThreadLocal.get();
        this.questionService.save(user.getId(), content);
    }

    public PageResult findBlacklist(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();

        IPage<BlackList> blackListIPage = this.blackListService.queryBlacklist(user.getId(), page, pageSize);

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setCounts(Convert.toInt(blackListIPage.getTotal()));
        pageResult.setPages(Convert.toInt(blackListIPage.getPages()));

        List<BlackList> records = blackListIPage.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }

        List<Object> userIds = CollUtil.getFieldValues(records, "blackUserId");
        List<UserInfo> userInfoList = this.userInfoService.findUserInfoByUserIds(userIds);

        List<BlackListVo> blackListVos = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            BlackListVo blackListVo = new BlackListVo();
            blackListVo.setAge(userInfo.getAge());
            blackListVo.setAvatar(userInfo.getLogo());
            blackListVo.setGender(userInfo.getSex().name().toLowerCase());
            blackListVo.setId(userInfo.getUserId());
            blackListVo.setNickname(userInfo.getNickName());

            blackListVos.add(blackListVo);
        }

        pageResult.setItems(blackListVos);

        return pageResult;
    }

    public void delBlacklist(Long userId) {
        User user = UserThreadLocal.get();
        this.blackListService.delBlacklist(user.getId(), userId);
    }

    public void updateNotification(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        User user = UserThreadLocal.get();
        this.settingsService.updateNotification(user.getId(), likeNotification, pinglunNotification, gonggaoNotification);
    }
}
